package optimizers.commons.evaluator;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import model.OligoSystemGeneral;

import fitness.Fitness;

import optimizers.ganeat.Species;

public class AsProcessFitnessEvaluator {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long startTime = System.currentTimeMillis();
		String fileEvaluator = args[0];
		String fileIn = args[1];
		String fileOut = args[2];
		int maxExec = Integer.parseInt(args[3]);
		if (maxExec != -1) {
			Timer timer = new Timer();
			TimerTask exitApp = new TimerTask() {
				public void run() {
					System.out.println(-1);
					System.exit(0);
				}
			};
			timer.schedule(exitApp, new Date(System.currentTimeMillis()
					+ maxExec * 1000));
		}

		FileInputStream readFile;
		FileOutputStream saveFile;
		try {
			readFile = new FileInputStream(fileEvaluator);
			ObjectInputStream restore = new ObjectInputStream(readFile);
			Fitness evaluator = (Fitness) restore.readObject();
			restore.close();
			readFile.close();

			readFile = new FileInputStream(fileIn);
			restore = new ObjectInputStream(readFile);
			OligoSystemGeneral oligoSystem = (OligoSystemGeneral) restore
					.readObject();
			restore.close();
			readFile.close();
			File file = new File(fileIn);
			file.delete();

			fitness.FitnessResult result = evaluator
					.evaluateFitness(oligoSystem);
			saveFile = new FileOutputStream(fileOut);
			ObjectOutputStream save = new ObjectOutputStream(saveFile);
			save.writeObject(result);
			save.close();
			saveFile.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		double estimatedTime = ((double) System.currentTimeMillis() - startTime) / 1000;
		System.out.println(estimatedTime);
		System.exit(0);
	}

}
